﻿using SmallJob.Model;
using SmallJob.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BackEnd.Controllers
{
    [Authorize]
    public class CategoryController : Controller
    {
        private readonly ICategoryService _CategoryService;
        public CategoryController(ICategoryService CategoryService)
        {
            _CategoryService = CategoryService;
        }

        //
        // GET: /Category/

        public ActionResult Index(string page, string filter)
        {
            if (string.IsNullOrWhiteSpace(page))
            {
                page = "1";
            }
            ViewData["tableindex"] = new { page = page, pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage), filter = filter };
            return View();
        }
        public ActionResult ConfigCategory()
        {
            var model = _CategoryService.GetTreeCategoryUse();
            return View(model);
        }
        [HttpPost]
        public ActionResult SaveConfigCategory()
        {
            var data = Request.Form.AllKeys;
            foreach (var item in data)
            {
                if (item.Contains("category-"))
                {

                    try
                    {
                        var id = Convert.ToInt32(item.Substring("category-".Length));
                        var value = Request.Form["category-" + id];
                        var parentid = Convert.ToInt32(value.Split('-')[0]);
                        var slot = Convert.ToInt32(value.Split('-')[1]);
                        var Category = _CategoryService.GetById(id);
                        Category.ParentID = parentid;
                        Category.DisplayNumber = slot;
                        _CategoryService.Update(Category);

                    }
                    catch (Exception)
                    {

                        ModelState.AddModelError("systemerror", "Error");
                    }

                }
            }
            if (ModelState.IsValid)
            {
                ViewData["result"] = "Success";
            }
            var model = _CategoryService.GetTreeCategoryUse();
            return View("ConfigCategory", model);
        }
        private SelectList GetListCategory(int selectedId)
        {
            var categorys = _CategoryService.GetAllAvaiable();
            var newCate = new Category { ID = 0, Name = "None" };
            categorys.Add(newCate);
            var selectlist = new SelectList(categorys, "ID", "Name", selectedId);
            return selectlist;
        }
        public ActionResult Add()
        {
            ViewData["isadd"] = true;
            ViewData["AllCate"] = this.GetListCategory(0);
            return View("Form");
        }
        public ActionResult Edit(int id)
        {
            ViewData["isadd"] = false;
            var model = _CategoryService.GetById(id);
            ViewData["AllCate"] = this.GetListCategory(model.ParentID);

            return View("Form", model);
        }
        public ActionResult Save()
        {
            int id = Convert.ToInt32(Request.Form["id"]);
            var category = _CategoryService.GetById(id);
            bool isadd = false;
            if (category == null)
            {
                isadd = true;
                category = new Category()
                {
                    ID = 0,
                    CreatedDate = DateTime.Now
                };
                category.ParentID = _CategoryService.GetAllAvaiable().FirstOrDefault().ID;
            }
            if (string.IsNullOrWhiteSpace(Request.Form["name"]))
            {
                ModelState.AddModelError("nameerror", "Name is required!");
            }
            else
                category.Name = Request.Form["name"];
            //category.ParentID = Convert.ToInt32(Request.Form["parentcateid"]);
            category.ModifiedDate = DateTime.Now;
            if (ModelState.IsValid)
            {
                if (isadd)
                {
                    _CategoryService.Add(category);
                }
                else
                {
                    _CategoryService.Update(category);
                }
                ViewData["isok"] = true;
            }


            ViewData["isadd"] = isadd;
            ViewData["AllCate"] = this.GetListCategory(category.ParentID);
            return View("Form", category);
        }
        public ActionResult Del(int id)
        {
            try
            {
                var Category = _CategoryService.GetById(id);
                Category.IsDeleted = true;
                _CategoryService.Update(Category);
                return Json(true);
            }
            catch (Exception)
            {

                return Json(false);
            }
        }
        [HttpPost]
        public ActionResult UnDel(int id)
        {
            try
            {
                var Category = _CategoryService.GetById(id);
                Category.IsDeleted = false;
                _CategoryService.Update(Category);
                return Json(true);
            }
            catch (Exception)
            {

                return Json(false);
            }
        }
        public ActionResult TableCategory(int page, int pagesize, string filter)
        {
            int total = 0;
            pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage);
            if (page == 0)
            {
                page = 1;
            }
            var model = _CategoryService.GetByPage(page, pagesize, out total);
            if (!string.IsNullOrWhiteSpace(filter))
            {
                model = _CategoryService.GetByPageFilter(page, pagesize, out total, filter);
                ViewData["filter"] = filter;
            }
            if ((total % pagesize) > 0)
            {
                ViewData["total"] = (total / pagesize) + 1;
            }
            else
            {
                ViewData["total"] = total / pagesize;
            }
            ViewData["curpage"] = page;
            ViewData["nextpage"] = page + 1;
            ViewData["prepage"] = page - 1;
            return PartialView(model);
        }

    }
}
